<template>
  <div class="order-list-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            clearable
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择订单状态" clearable style="width: 180px">
            <el-option v-for="item in orderTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        row-key="id"
        stripe
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" fixed="left" />
        <el-table-column prop="id" label="订单号" width="80" align="center" fixed="left" />
        <el-table-column prop="customerName" label="客户名称" width="120" show-overflow-tooltip />
        <el-table-column prop="productName" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="quantity" label="数量" width="70" align="center" />
        <el-table-column prop="orderDate" label="下单时间" width="150" align="center" />
        <el-table-column prop="status" label="订单状态" width="90" align="center">
          <template #default="scope">
            <el-tag :type="getOrderStausTypeTag(scope.row.status)">
              {{ getOrderStausTypeLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="90" align="center">
          <template #default="scope">
            <el-tag :type="getPaymentMethodTag(scope.row.paymentMethod)">
              {{ getPaymentMethodLabel(scope.row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentAmount" label="支付金额" width="110" align="right">
          <template #default="scope">
            <span>{{ formatCurrency(scope.row.paymentAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 订单编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑订单信息" width="550px" @close="resetForm" destroy-on-close>
      <el-form ref="orderFormRef" :model="orderForm" :rules="orderFormRules" label-width="90px" status-icon>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="orderForm.customerName" placeholder="请输入客户名称" disabled />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="orderForm.productName" placeholder="请输入商品名称" disabled />
        </el-form-item>
        <el-form-item label="购买数量" prop="quantity">
          <el-input-number
            v-model="orderForm.quantity"
            controls-position="right"
            :min="1"
            :max="1000"
            placeholder="请输入购买数量"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderDate">
          <el-input v-model="orderForm.orderDate" placeholder="请输入下单时间" disabled />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="orderForm.status" placeholder="请选择订单状态" style="width: 100%">
            <el-option
              v-for="option in orderTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="orderForm.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
            <el-option
              v-for="option in paymentMethodOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="paymentAmount">
          <el-input-number
            v-model="orderForm.paymentAmount"
            :min="0"
            :precision="2"
            :step="100"
            controls-position="right"
            style="width: 100%"
            placeholder="请输入支付金额"
            :formatter="(value) => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="(value) => value.replace(/[^\d.]/g, '')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { deleteOrders, getOrderList, updateOrder } from "@/api/order";
import { getOrderListExcel } from "@/api/export";

// 订单状态选项
const orderTypeOptions = [
  { value: 0, label: "待付款", type: "" },
  { value: 1, label: "已付款", type: "success" },
  { value: 2, label: "已发货", type: "warning" },
  { value: 3, label: "已完成", type: "info" },
  { value: 4, label: "已取消", type: "danger" },
];

// 支付方式选项
const paymentMethodOptions = [
  { value: 1, label: "支付宝", type: "success" },
  { value: 2, label: "微信", type: "warning" },
  { value: 3, label: "银行卡", type: "info" },
];

// 搜索表单
const searchForm = reactive({
  customerName: "",
  productName: "",
  dateRange: [],
  status: "",
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const selectedRows = ref([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 对话框
const dialogVisible = ref(false);
const orderFormRef = ref(null);
const orderForm = reactive({
  id: null,
  customerName: "",
  productName: "",
  quantity: "",
  orderDate: "",
  status: "",
  paymentMethod: "",
  paymentAmount: "",
});

// 表单验证规则
const orderFormRules = {
  quantity: [{ required: true, message: "请输入购买数量", trigger: "blur" }],
  status: [{ required: true, message: "请选择订单状态", trigger: "change" }],
  paymentMethod: [{ required: true, message: "请选择付款方式", trigger: "change" }],
  paymentAmount: [{ required: true, message: "请输入支付金额", trigger: "blur" }],
};

// 初始化
onMounted(() => {
  fetchOrderList();
});

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true;

  try {
    const response = await getOrderList({
      ...searchForm,
      current: pagination.currentPage,
      size: pagination.pageSize,
    });

    if (response.success) {
      pagination.total = response.data.total;
      tableData.value = response.data.list;
    } else {
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取订单状态标签类型
const getOrderStausTypeTag = (status) => {
  const option = orderTypeOptions.find((item) => item.value === status);
  return option ? option.type : "";
};

// 获取订单状态标签文本
const getOrderStausTypeLabel = (status) => {
  const option = orderTypeOptions.find((item) => item.value === status);
  return option ? option.label : "";
};

// 获取支付方式标签类型
const getPaymentMethodTag = (paymentMethod) => {
  const option = paymentMethodOptions.find((item) => item.value === paymentMethod);
  return option ? option.type : "";
};

// 获取支付方式标签文本
const getPaymentMethodLabel = (paymentMethod) => {
  const option = paymentMethodOptions.find((item) => item.value === paymentMethod);
  return option ? option.label : "";
};

// 格式化货币
const formatCurrency = (value) => {
  if (value === undefined || value === null) return "¥0.00";
  return `¥ ${value.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
};

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchOrderList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    if (key === "dateRange") {
      searchForm[key] = [];
    } else {
      searchForm[key] = "";
    }
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchOrderList();
};

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchOrderList();
};

// 编辑订单
const handleEdit = (row) => {
  Object.keys(orderForm).forEach((key) => {
    orderForm[key] = row[key];
  });
  dialogVisible.value = true;
};

// 删除订单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除客户 "${row.customerName}"的订单信息吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteOrders([row.id]);
    if (response.success) {
      ElMessage.success("删除成功");
      fetchOrderList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除订单失败:", error);
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的订单");
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个订单信息吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteOrders(selectedRows.value.map((row) => row.id));
    if (response.success) {
      ElMessage.success("批量删除成功");
      fetchOrderList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除订单失败:", error);
    }
  }
};

// 导出
const handleExport = async () => {
  await getOrderListExcel();
  ElMessage.success("导出成功");
};

// 提交表单
const submitForm = async () => {
  if (!orderFormRef.value) return;

  try {
    const valid = await orderFormRef.value.validate();
    if (!valid) return;

    const response = await updateOrder(orderForm);
    if (response.success) {
      ElMessage.success("更新成功");
      dialogVisible.value = false;
      fetchOrderList();
    }
  } catch (error) {
    console.error("更新订单失败:", error);
  }
};

// 重置表单
const resetForm = () => {
  if (orderFormRef.value) {
    orderFormRef.value.resetFields();
  }
};
</script>

<style scoped>
.order-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 搜索过滤区样式 */
.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

/* 表格区域 */
.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

:deep(.el-table__row td) {
  padding: 10px 0;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding: 15px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
}
</style>
